package me.yobol.lintcode.easy.rotatestring;

/**
 *
 * @author Yobol
 */
public class ShellReverseRotateString implements IRotateString{
    
    /**
     * 将字符串分为2段，
     * 先分别将第1段，第2段逆序，
     * 然后再将整个字符串逆序
     * 
     * @param str
     * @param offset
     * @return 
     */
    @Override
    public char[] rotateString(char[] str ,int offset){
        if (str == null || str.length == 0) {
            return str;
        }
        
        char[] res = new char[str.length];
        System.arraycopy(str, 0, res, 0, str.length);
        offset %= str.length;
        reverse(res,0,res.length - offset - 1);
        reverse(res,res.length - offset,res.length - 1);
        reverse(res,0,res.length - 1);
        return res;
    }
    
    /**
     * 将字符串逆序
     * 
     * @param str
     * @param start
     * @param end 
     */
    private static void reverse(char[] str,int start,int end){
        char temp;
        for (int i = start,j = end; i < j; i++,j--) {
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
        }
    }
}
